<?php

namespace app\models\article;

use app\models\constant\Status;
use app\models\Images;
use Yii;

/**
 * This is the model class for table "article".
 *
 * @property int $id
 * @property int $category_id
 * @property string $title
 * @property int $image_id
 * @property string|null $content
 * @property string $create_time
 * @property string $update_time
 * @property int $status 1 正常 0 关闭 -99删除
 * @property int $sort
 * @property int $view 浏览次数
 * @property int $view_virtual 虚拟浏览
 * @property string|null $keyword 以空格, 逗号分隔
 */
class Article extends \yii\db\ActiveRecord
{
    use Status;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'article';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['category_id', 'image_id', 'status', 'sort', 'view', 'view_virtual'], 'integer'],
            [['content', 'keyword'], 'string'],
            [['create_time', 'update_time'], 'safe'],
            [['title'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'category_id' => 'Category ID',
            'title' => 'Title',
            'image_id' => 'Image ID',
            'content' => 'Content',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
            'status' => 'Status',
            'sort' => 'Sort',
            'view' => 'View',
            'view_virtual' => 'View Virtual',
            'keyword' => 'Keyword',
        ];
    }

    /**
     * Save timestamp
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $time = date('Y-m-d H:i:s');
            $this->update_time = $time;
            if ($insert) {
                $this->create_time = $time;
            }
            return true;
        }
        return false;
    }

    /**
     * with image
     *
     * @return \yii\db\ActiveQuery
     */
    public function getImage()
    {
        return $this->hasOne(Images::class, ['id' => 'image_id']);
    }

    public function getCategory()
    {
        return $this->hasOne(ArticleCategory::class, ['id' => 'category_id']);
    }

    // 收藏时重复了
    public function getMainImage()
    {
        return $this->hasOne(Images::class, ['id' => 'image_id']);
    }
}
